package com.imooc.miaosha.exception;

import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 全局的异常处理
 *
 * @author XX
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 全局异常拦截
     * <note>需要返回给前端什么信息，就返回什么信息， 建议前后返回的都是此信息，保证前端好统一处理</note>
     *
     * @param exception 后台抛出的异常信息
     * @return 结果包裹类
     */
    @ExceptionHandler(value = Exception.class)
    public Result<String> exceptionHandler(Exception exception) {
        //开发阶段建议打印
        exception.printStackTrace();
        if (exception instanceof GlobalException) {
            GlobalException ex = (GlobalException) exception;
            return Result.error(ex.getCm());
        } else if (exception instanceof BindException) {
            BindException ex = (BindException) exception;
            //可能是多个错误信息
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        } else {
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
